package com.example.secondhandshop.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.secondhandshop.R;
import com.example.secondhandshop.bean.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SignupActivity extends AppCompatActivity {
    private Boolean bPwdshow = false;
    private EditText etPwd;
    private EditText etuser;
    private Button btn_signup;
private void sendCredentialsToServer(String username, String password) { //将账号密码传入后端
    OkHttpClient client = new OkHttpClient();
    String url = Constans.SERVER_URL()+"tran/user/register";
    Headers headers = new Headers.Builder()
            .add("appId", Constans.getAppId())
            .add("appSecret", Constans.getAppSecret())
            .add("Accept", "application/json, text/plain, */*")
            .build();
    Map<String, Object> bodyMap = new HashMap<>();
    bodyMap.put("password",password);
    bodyMap.put("username", username);
    // 将Map转换为字符串类型加入请求体中
    Gson gson=new Gson();
    String body = gson.toJson(bodyMap);
    MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    Request request = new Request.Builder()
            .url(url)
            .headers(headers)
            .post(RequestBody.create(MEDIA_TYPE_JSON, body))
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e("网络请求", "请求失败： " + e.getMessage());
            System.out.println("失败");
            e.printStackTrace();
        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                Log.i("网络请求", "请求成功，状态码： " + response.code());
                Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
                // 获取响应体的json串
                String body = response.body().string();
                Log.d("info", body);
                // 解析json串到自己封装的状态
                ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
                Log.d("info", dataResponseBody.toString());
                finish();
            }
        }
    });
}
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_signup);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        final ImageView passshow = findViewById(R.id.pwd_show1);
        etPwd = findViewById(R.id.new_password);
        etuser = findViewById(R.id.new_user);
        btn_signup = findViewById(R.id.true_signup);
        passshow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bPwdshow = !bPwdshow;
                if (bPwdshow) {
                    passshow.setImageResource(R.drawable.baseline_visibility_24);
                    etPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    passshow.setImageResource(R.drawable.baseline_visibility_off_24);
                    etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    etPwd.setTypeface(Typeface.DEFAULT);
                }
            }
        });
        btn_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etuser.getText().toString();
                String password = etPwd.getText().toString();
                if (TextUtils.isEmpty(username)) {
                    Toast.makeText(SignupActivity.this, "新用户名不能为空", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(password)) {
                    Toast.makeText(SignupActivity.this, "新密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    sendCredentialsToServer(username, password);
                }
            }
        });
    }
}
